"""
数据库执行引擎的数据类型定义
"""

from typing import Any, Dict, List, Optional, Union, Tuple, Iterator
from enum import Enum
from dataclasses import dataclass
import time

# 基础数据类型
DataValue = Union[int, float, str, bool, bytes, None]
Record = Dict[str, DataValue]
RecordBatch = List[Record]

# 操作符类型
class OperatorType(Enum):
    """操作符类型枚举"""
    TABLE_SCAN = "table_scan"
    INDEX_SCAN = "index_scan"
    FILTER = "filter"
    PROJECT = "project"
    HASH_JOIN = "hash_join"
    NESTED_LOOP_JOIN = "nested_loop_join"
    SORT_MERGE_JOIN = "sort_merge_join"
    HASH_AGGREGATE = "hash_aggregate"
    SORT_AGGREGATE = "sort_aggregate"
    SORT = "sort"
    LIMIT = "limit"
    UNION = "union"
    INTERSECT = "intersect"
    EXCEPT = "except"
    # DDL操作
    CREATE_TABLE = "create_table"
    DROP_TABLE = "drop_table"
    # Database级DDL操作
    CREATE_DATABASE = "create_database"
    DROP_DATABASE = "drop_database"
    USE_DATABASE = "use_database"
    LIST_DATABASES = "list_databases"
    # DML操作
    INSERT = "insert"
    UPDATE = "update"
    DELETE = "delete"
    # 权限管理操作
    GRANT = "grant"
    REVOKE = "revoke"
    # 用户管理操作
    CREATE_USER = "create_user"
    DROP_USER = "drop_user"

# 连接类型
class JoinType(Enum):
    """连接类型枚举"""
    INNER = "inner"
    LEFT = "left"
    RIGHT = "right"
    FULL = "full"
    CROSS = "cross"

# 聚合函数类型
class AggregateFunction(Enum):
    """聚合函数类型"""
    COUNT = "count"
    SUM = "sum"
    AVG = "avg"
    MIN = "min"
    MAX = "max"
    GROUP_CONCAT = "group_concat"

# 排序方向
class SortDirection(Enum):
    """排序方向"""
    ASC = "asc"
    DESC = "desc"

# 数据类型
class DataType(Enum):
    """数据类型枚举"""
    INTEGER = "integer"
    BIGINT = "bigint"
    FLOAT = "float"
    DOUBLE = "double"
    VARCHAR = "varchar"
    TEXT = "text"
    BOOLEAN = "boolean"
    DATE = "date"
    TIMESTAMP = "timestamp"
    BLOB = "blob"

@dataclass
class ColumnInfo:
    """列信息"""
    name: str
    data_type: DataType
    nullable: bool = True
    default_value: Optional[DataValue] = None
    max_length: Optional[int] = None

@dataclass
class TableInfo:
    """表信息"""
    name: str
    columns: List[ColumnInfo]
    primary_key: Optional[List[str]] = None
    indexes: Optional[List[str]] = None

@dataclass
class IndexInfo:
    """索引信息"""
    name: str
    table_name: str
    columns: List[str]
    unique: bool = False
    clustered: bool = False

@dataclass
class ExecutionContext:
    """执行上下文"""
    transaction_id: Optional[str] = None
    user_id: Optional[str] = None
    session_id: Optional[str] = None
    start_time: float = None
    timeout: Optional[int] = None
    
    def __post_init__(self):
        if self.start_time is None:
            self.start_time = time.time()

@dataclass
class ExecutionStats:
    """执行统计信息"""
    rows_processed: int = 0
    rows_returned: int = 0
    execution_time_ms: float = 0
    memory_used_bytes: int = 0
    io_operations: int = 0
    cpu_time_ms: float = 0

# 异常类型
class ExecutionError(Exception):
    """执行引擎异常基类"""
    pass

class QueryExecutionError(ExecutionError):
    """查询执行异常"""
    pass

class MemoryExhaustedException(ExecutionError):
    """内存耗尽异常"""
    pass

class TransactionAbortedException(ExecutionError):
    """事务中止异常"""
    pass

class TimeoutException(ExecutionError):
    """超时异常"""
    pass

# 隔离级别枚举（从transaction_manager移动到这里以避免循环导入）
class IsolationLevel(Enum):
    """隔离级别"""
    READ_UNCOMMITTED = "read_uncommitted"
    READ_COMMITTED = "read_committed"
    REPEATABLE_READ = "repeatable_read"
    SERIALIZABLE = "serializable"

